/*jshint esversion: 9 */
//promise 工具类
class MyPromise{  //只实现了resolve,其他都差不多
    constructor(callback){
        this.promiseState = "pending";  //promise的状态 fulfilled rejected
        this.promiseResult = undefined;  //保存成功后的结果
        callback((param)=>{  //由外部调用所以此时必须是箭头函数
            if(param instanceof MyPromise){  //如果自身的数据是一个promise对象
                param.then((_param)=>{
                    this.resolve(_param);
                });
            }else{
                this.resolve(param);
            }
        });
    }
    resolve(data){
        queueMicrotask(()=>{  //必须在微任务执行后再确定状态
            this.promiseState = 'fulfilled';
            this.promiseResult = data;
            if(!this.resolveCallback) return;
            this.resolveCallback(data);
        });
    }
    then(resolve){  //注册回调
        return new MyPromise((_resolve)=>{
            this.resolveCallback = function(promiseResult){  //组装本次对象的回调函数
                _resolve(resolve(promiseResult));
            };
            if(this.promiseState === 'fulfilled'){  //如果状态确定了的话，可以直接返回内部 promiseResult
                this.resolve();
            }
        });
    }
}
new MyPromise((resolve)=>{
    console.log(1);
    resolve(new MyPromise(r=>r(2)));
}).then((res)=>{
    console.log(res);
});